package com.project_test.kun.travelling_1st.GoodsDetailActivities.CarDetail;

import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Cache;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.project_test.kun.travelling_1st.R;
import com.project_test.kun.travelling_1st.Utils.CustomVolley;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/*
*
* http://www.handybest.com/index.php?m=Api&c=Vehicle&a=vehicleDetail&vid=
* 1000117
* &device_token=864394010925172&push_token=48c3e0cad9df6d2e4446b318711cdb7e09784448&mobile_type=Android&mobile_model=GT-N7100%2C4.4.2&version_code=10000
*
* */
public class CarDetailActivity extends AppCompatActivity {
    private String detailPath;
    private RequestQueue mRequestQueue;
    private CarDetailBean carDetailBean;
    private JSONObject originalJson;
    private ViewPager carDetailPicList;
    //    private MAdapter mAdapter;
    private ImageView[] mImageViews;
    private List<ImageView> imgs;
    private TextView carDetailTitle,
            catDetailBrand, carDetailModel, carDetailVehicleTypeName, carDetailPeopleNum, carDetailBaggageNum, carDetailLongService,
            carDetailServiceMileage, carDetailPriceInvolve, carDetailPriceNoinvolve, carDetailExceedIntro, carDetailServiceTranslate, carDetailServiceGuide,
            carDetailServiceOther, carDetailDriverIntro, carDetailComment;


    Handler hander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                originalJson = (JSONObject) msg.obj;
                parseJson(originalJson);
            }
            if (msg.what==2){
                insertData();
            }
        }
    };

    private void parseJson(JSONObject jsonObject) {
        try {
            JSONObject obj = jsonObject.optJSONObject("data");
            carDetailBean.parseJson(obj);
            hander.sendEmptyMessage(2);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_detail);
        detailPath = getIntent().getStringExtra("detailPath");
        initView();
        jsonRequest(detailPath);
        carDetailBean = new CarDetailBean();
    }

    private void insertData() {
        carDetailTitle.setText(carDetailBean.getTitle());
        catDetailBrand.setText(carDetailBean.getVehicle_brands());
        carDetailModel.setText(carDetailBean.getVehicle_model());
        carDetailVehicleTypeName.setText(carDetailBean.getVehicle_type_name());
        carDetailPeopleNum.setText("乘坐"+carDetailBean.getPeople_num()+"人");
        carDetailBaggageNum.setText(carDetailBean.getBaggage_num()+"件行李");
        carDetailLongService.setText(carDetailBean.getLong_service()+"小时");
        carDetailServiceMileage.setText(carDetailBean.getService_mileage()+"km");
        carDetailPriceInvolve.setText(carDetailBean.getPrice_involve());
        carDetailPriceNoinvolve.setText(carDetailBean.getPrice_noinvolve());
        carDetailExceedIntro.setText(carDetailBean.getExceed_intro());
        carDetailServiceTranslate.setText(carDetailBean.getService_translate().equals("1")?"英语":"汉语");
        carDetailServiceGuide.setText(carDetailBean.getService_guide().equals("2")?"不含导游服务":"含导游服务");
        carDetailServiceOther.setText(carDetailBean.getService_other());
        carDetailDriverIntro.setText(carDetailBean.getDriver_intro());
        initHeadPager();
    }

    private void initHeadPager() {

        for (int i = 0; i < carDetailBean.getPicList().length(); i++) {
            ImageView imageViewtmp = new ImageView(getBaseContext());
//            imageViewtmp.setBackgroundResource(R.mipmap.rec_logo);
            imageViewtmp.setAdjustViewBounds(true);
            imageViewtmp.setScaleType(ImageView.ScaleType.FIT_XY);
            imageViewtmp.setAdjustViewBounds(true);
            imageViewtmp.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
            Picasso.with(getBaseContext()).load(carDetailBean.getPiclists()[i]).into(imageViewtmp);
//            mImageViews=new ImageView[];
            imgs=new ArrayList<>();
            imgs.add(imageViewtmp);

//            mImageViews.add(imageViewtmp);
        }

//        carDetailPicList.setAdapter(mAdapter);


    }

    private void initView() {
        carDetailPicList= (ViewPager) findViewById(R.id.car_detail_piclist);
        carDetailTitle = (TextView) findViewById(R.id.car_detail_title);
        catDetailBrand = (TextView) findViewById(R.id.car_detail_brand);
        carDetailModel = (TextView) findViewById(R.id.car_detail_model);
        carDetailVehicleTypeName = (TextView) findViewById(R.id.car_detail_vehicle_type_name);
        carDetailPeopleNum = (TextView) findViewById(R.id.car_detail_people_num);
        carDetailBaggageNum = (TextView) findViewById(R.id.car_detail_baggage_num);
        carDetailLongService = (TextView) findViewById(R.id.car_detail_long_service);
        carDetailServiceMileage = (TextView) findViewById(R.id.car_detail_service_mileage);
        carDetailPriceInvolve = (TextView) findViewById(R.id.car_detail_price_involve);
        carDetailPriceNoinvolve = (TextView) findViewById(R.id.car_detail_price_noinvolve);
        carDetailExceedIntro = (TextView) findViewById(R.id.car_detail_exceed_intro);
        carDetailServiceTranslate = (TextView) findViewById(R.id.car_detail_service_translate);
        carDetailServiceGuide = (TextView) findViewById(R.id.car_detail_service_guide);
        carDetailServiceOther = (TextView) findViewById(R.id.car_detail_service_other);
        carDetailDriverIntro = (TextView) findViewById(R.id.car_detail_driver_intro);
        carDetailComment = (TextView) findViewById(R.id.car_detail_comment);
    }

    private void jsonRequest(final String path) {
        mRequestQueue = CustomVolley.getInstance(this).sRequestQueue;
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(JsonObjectRequest.Method.GET,
                path, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Message msg = new Message();
                msg.what = 1;
                msg.obj = response;
                hander.sendMessage(msg);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //            获取缓存
                Cache cache = mRequestQueue.getCache();
                if (cache != null) {
                    Cache.Entry entry = cache.get(path);
                    if (entry != null) {
                        byte[] data = entry.data;
                        if (data != null) {
                            try {
                                String result = new String(data, "UTF-8");
                                JSONObject obj = new JSONObject(result);
                                Message msg = new Message();
                                msg.obj = obj;
                                hander.sendMessage(msg);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        });
        mRequestQueue.add(jsonObjectRequest);
    }

    class MyAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager)container).removeView(mImageViews[position % mImageViews.length]);

        }

        /**
         * 载入图片进去，用当前的position 除以 图片数组长度取余数是关键
         */
        @Override
        public Object instantiateItem(View container, int position) {
            ((ViewPager)container).addView(mImageViews[position % mImageViews.length], 0);
            return mImageViews[position % mImageViews.length];
        }



    }



}
